package br.cin.ufpe.feedbacktest.core;

import java.lang.reflect.Constructor;

public class ClassToString {
	
	public static String parameterPrint(Class<?> parameterClass){
		StringBuilder buf = new StringBuilder();
		
		if(parameterClass.isPrimitive() ||
			parameterClass.equals(String.class)){
			buf.append(printPrimitive(parameterClass));
		}else{
		
		buf.append("new ");
		buf.append(parameterClass.getName());
		
		Constructor<?>[] constructors = parameterClass.getConstructors();
		int indexConstructor = constructorEmpty(constructors);
		if(indexConstructor != -1){
			buf.append("()");
		}else{
			indexConstructor = RandomFactory.randomNumberBetween(0, constructors.length);
			Constructor<?> constructor = constructors[indexConstructor];
			buf.append("(");
			buf.append(constructorPrint(constructor));
			buf.append(")");
		}
		
		}
		
		
		return buf.toString();
	}	
	
	private static String constructorPrint(Constructor<?> constructor){
		StringBuilder buf = new StringBuilder();
		Class<?>[] constructorParameters = constructor.getParameterTypes();
		Class<?> parameterClass = null;
		
		for(int index =0; index< constructorParameters.length; index++){
			parameterClass = constructorParameters[index];
			buf.append(parameterPrint(parameterClass));
			if(index < constructorParameters.length - 1){
				buf.append(",");
			}
		}
		
		return buf.toString();
	}
	
	private static String printPrimitive(Class<?> primitiveClass){
		String ret = null;
		
		if(primitiveClass.equals(String.class)){
			ret = "";
		}
		if (primitiveClass.equals(byte.class)) {				
			byte b = (byte) RandomFactory.randomNumber();				
			ret = String.valueOf(b);

		} else if (primitiveClass.equals(short.class)) {
			short s = (short) RandomFactory.randomNumber();				
			ret = String.valueOf(s);

		} else if (primitiveClass.equals(int.class)) {
			int i = RandomFactory.randomNumber();				
			ret = String.valueOf(i);

		} else if (primitiveClass.equals(long.class)) {
			long l = (long) RandomFactory.randomNumber();				
			ret = String.valueOf(l);

		} else if (primitiveClass.equals(float.class)) {
			float f = (float) RandomFactory.randomDecimal();				
			ret = String.valueOf(f);

		} else if (primitiveClass.equals(double.class)) {
			double d = RandomFactory.randomDecimal();				
			ret = String.valueOf(d);

		} else if (primitiveClass.equals(char.class)) {
			char c = RandomFactory.randomChar();				
			ret = String.valueOf(c);

		} else if (primitiveClass.equals(boolean.class)) {
			boolean b = RandomFactory.randomBoolean();				
			ret = String.valueOf(b);
		}
		
		return ret;
	}
	
	
	
	private static int constructorEmpty(Constructor<?>[] constructors){
		int ret = -1;
		
		for(int index = 0; index< constructors.length;index++){
			Constructor<?> c = constructors[index];
			if(c.getParameterTypes().length == 0){
				ret = index;
				break;
			}
		}
		
		return ret;
	}

}
